package com.yu.crm.config;

import com.yxzz.common.BaseResponse;
import com.yxzz.common.config.UserCacheManager;
import com.yxzz.common.constant.CommonKeys;
import com.yxzz.common.constant.ExceptionCodes;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.JsonHelpers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Optional;


/**
 * 模块名称：
 * 功能说明： 自定义拦截器
 * @Author: song
 */
@Component
public class InterceptorConfig  extends HandlerInterceptorAdapter {

    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //获取传来的参数accessToken
            Object accessToken = Optional.ofNullable(request.getParameter(CommonKeys.TOKEN))
                    .orElse(request.getHeader(CommonKeys.TOKEN));
            if (DataHelpers.isEmpty(accessToken)) {
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                response.reset();
                response.setContentType("application/json");
                writer.print(JsonHelpers.toJson(BaseResponse.failure(ExceptionCodes.LOGIN_FAILED, "权限验证失败：token为空"))
                        .orElse("{\"status\":\"" + ExceptionCodes.LOGIN_FAILED + "\",\"msg\":\"登录验证失败，请重新登录！\"}"));
                writer.flush();
                writer.close();
            } else {
                if (!userCacheManager.validate(String.valueOf(accessToken))) {
                        response.setCharacterEncoding("UTF-8");
                        PrintWriter writer = response.getWriter();
                        response.reset();
                        response.setContentType("application/json");
                        writer.print(JsonHelpers.toJson(BaseResponse.failure(ExceptionCodes.LOGIN_FAILED, "网关权限验证失败：token失效，token={}"+accessToken))
                                .orElse("{\"status\":\"" + ExceptionCodes.LOGIN_FAILED + "\",\"msg\":\"登录验证失败，请重新登录！\"}"));
                    writer.flush();
                    writer.close();
                }
            }
        } catch (Exception e) {
            throw new GeneralException("权限验证异常:,error={}"+ e.getMessage());
        }
        return true;
    }

}
